﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Rookey.Frame.IMWeb;
using Newtonsoft.Json;

public partial class Login : System.Web.UI.Page
{
	static string[] UserDirs = new string[] { "Config", "Home", "pub", "Temp" };

	protected void Page_Load(object sender, EventArgs e)
	{
		String sessionId = Guid.NewGuid().ToString().ToUpper();
        TempUserInfo userInfo = null;
        FormsIdentity identity = Context.User.Identity as FormsIdentity;
        if (identity != null)
        {
            string[] token = identity.Ticket.UserData.Split("___".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            if (token != null && token.Length > 0)
            {
                userInfo = JsonConvert.DeserializeObject<TempUserInfo>(token[0]);
            }
        }
		if (IsPostBack)
		{
            if (userInfo == null)
            {
                try
                {

                    if (Request.Params["login"] != null)
                    {
                        HtmlInputText txtUser = FindControl("txtuser") as HtmlInputText;
                        HtmlInputText txtPwd = FindControl("txtpwd") as HtmlInputText;
                        LoginUser(sessionId, txtUser.Value, txtPwd.Value);
                        
                    }
                    else if (Request.Params["register"] != null)
                    {
                        string user = Request.Params["txtuser_reg"];
                        string nickname = Request.Params["txtnick_reg"];
                        string pwd = Request.Params["txtpwd_reg"];
                        string email = Request.Params["txtemail_reg"];

                        if (Rookey.Frame.IMCore.AccountImpl.Instance.GetUserInfo(user) != null) throw new Exception(string.Format("用户\"{0}\"已存在！", user));

                        Rookey.Frame.IMCore.AccountImpl.Instance.CreateUser(user, nickname, pwd, email);

                        LoginUser(sessionId, user, pwd);
                    }
                }
                catch (Exception ex)
                {
                    (FindControl("status") as HtmlInputHidden).Value = "error";
                    (FindControl("data") as HtmlInputHidden).Value = ex.Message;
                }
            }
            else
            {
                HttpCookie cookie = new HttpCookie("IM", userInfo.UserName);
                cookie.Expires = DateTime.Now.AddMinutes(30);
                Context.Response.Cookies.Add(cookie);
                (FindControl("status") as HtmlInputHidden).Value = "login";
                (FindControl("data") as HtmlInputHidden).Value = Rookey.Frame.IMCore.Utility.RenderHashJson(
                    "UserInfo", Rookey.Frame.IMCore.AccountImpl.Instance.GetUserInfo(userInfo.UserName).DetailsJson
                );
                Rookey.Frame.IMCore.SessionManagement.Instance.GetAccountState(userInfo.UserName).NewSession(sessionId);
            }
		}
		else
		{
            if (userInfo == null)
            {
                if (!String.IsNullOrEmpty(Rookey.Frame.IMCore.ServerImpl.Instance.GetUserName(Context))
                     && Request.QueryString["auto"] != "false")
                {
                    (FindControl("status") as HtmlInputHidden).Value = "login";
                    (FindControl("data") as HtmlInputHidden).Value = Rookey.Frame.IMCore.Utility.RenderHashJson(
                        "UserInfo", Rookey.Frame.IMCore.ServerImpl.Instance.GetCurrentUser(Context).DetailsJson
                    );

                    Rookey.Frame.IMCore.SessionManagement.Instance.GetAccountState(Rookey.Frame.IMCore.ServerImpl.Instance.GetCurrentUser(Context).Name).NewSession(sessionId);
                }
            }
            else
            {
                HttpCookie cookie = new HttpCookie("IM", userInfo.UserName);
                cookie.Expires = DateTime.Now.AddMinutes(30);
                Context.Response.Cookies.Add(cookie);
                (FindControl("status") as HtmlInputHidden).Value = "login";
                var accountInfo = Rookey.Frame.IMCore.AccountImpl.Instance.GetUserInfo(userInfo.UserName);
                if (accountInfo != null)
                {
                    (FindControl("data") as HtmlInputHidden).Value = Rookey.Frame.IMCore.Utility.RenderHashJson(
                        "UserInfo", accountInfo.DetailsJson
                    );
                    Rookey.Frame.IMCore.SessionManagement.Instance.GetAccountState(userInfo.UserName).NewSession(sessionId);
                }
            }
		}
        (FindControl("sessionId") as HtmlInputHidden).Value = sessionId;
    }

    /// <summary>
    /// 登录用户
    /// </summary>
    /// <param name="sessionId">sessionid</param>
    /// <param name="username">用户名</param>
    /// <param name="pwd">密码</param>
    private void LoginUser(string sessionId, string username, string pwd)
    {
        if (Rookey.Frame.IMCore.AccountImpl.Instance.Validate(username, pwd))
        {
            foreach (string dir in UserDirs)
            {
                String path = String.Format("/{0}/{1}", username, dir);
                if (!Rookey.Frame.IMCore.IO.Directory.Exists(path)) Rookey.Frame.IMCore.IO.Directory.CreateDirectory(path);
            }

            (FindControl("status") as HtmlInputHidden).Value = "login";
            (FindControl("data") as HtmlInputHidden).Value = Rookey.Frame.IMCore.Utility.RenderHashJson(
                "UserInfo", Rookey.Frame.IMCore.AccountImpl.Instance.GetUserInfo(username).DetailsJson
            );

            Rookey.Frame.IMCore.ServerImpl.Instance.Login(sessionId, Context, username, null);
        }
        else
        {
            throw new Exception("用户不存在或密码错误！");
        }
    }
}
